//
//  HMEmoticonTools.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/10/6.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
//每页显示20个表情按钮
let NumberOfPage = 20
//最近表情归档和解档路径
let RecentDataPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recentEmoticonArray.archiver")
//读取表情工具类
class HMEmoticonTools: NSObject {

    static let sharedTools:HMEmoticonTools = HMEmoticonTools()
    //构造函数私有化
    private override init() {
        super.init()
        
        
    }
    
    //获取bundle对象
    lazy var emoticonBundle:Bundle = {
        //获取bundle路径
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)!
        //根据路径创建bundle对象
        let bundle = Bundle(path: path)!
        return bundle
    }()
    
    //给表情视图提供数据
    lazy var allEmoticonsArray:[[[HMEmoticon]]] = {
        return [[self.recentEmoticonArray],
            self.sectionEmoticon(emoticonArray: self.defaultEmoticonArray),
        self.sectionEmoticon(emoticonArray: self.emojiEmoticonArray),
        self.sectionEmoticon(emoticonArray: self.lxhEmoticonArray)
        ]
    }()
    
    //最近表情
    private lazy var recentEmoticonArray:[HMEmoticon] = {

        //获取本地最近表情数据
        if let localRecentData = self.loadRecentEmoticonArray() {
            //如果本地有最近表情数据，直接返回
            return localRecentData
        }else {
            //如果本地没有最近表情数据，返回空数组
            let emoticonArray = [HMEmoticon]()
            return emoticonArray
        }
        
    }()
    
    //获取默认表情数据
    private lazy var defaultEmoticonArray:[HMEmoticon] = {
        return self.loadEmoticonArray(folderName:"default",fileName:"info.plist")
    }()
    //获取emoji表情数据
    private lazy var emojiEmoticonArray:[HMEmoticon] = {
        return self.loadEmoticonArray(folderName:"emoji",fileName:"info.plist")
    }()
    //获取浪小花表情数据
    private lazy var lxhEmoticonArray:[HMEmoticon] = {
        return self.loadEmoticonArray(folderName:"lxh",fileName:"info.plist")
    }()
    
    //读取表情数据的方法
    private func loadEmoticonArray(folderName:String,fileName:String)->[HMEmoticon] {
        //获取文件路径
        let subPath = folderName + "/" + fileName
        let path = self.emoticonBundle.path(forResource: subPath, ofType: nil)!
        //获取资源数据
        let dicArray = NSArray(contentsOfFile: path) as! [[String:Any]]
        //字典转模型
        let modelArray = NSArray.yy_modelArray(with: HMEmoticon.self, json: dicArray) as! [HMEmoticon]
        //遍历数组模型，如果是图片需要拼接路径
        for model in modelArray {
            if model.type == "0" {
                let imagePath = self.emoticonBundle.path(forResource: folderName, ofType: nil)! + "/" + model.png!
                model.path = imagePath
                model.folderName = folderName
            }
        }
        return modelArray
        
        
    }
    
    //把表情数组拆分成二维数组的方法
    private func sectionEmoticon(emoticonArray:[HMEmoticon])->[[HMEmoticon]] {
        //根据数组的个数计算页数
        let pageCount = (emoticonArray.count - 1) / NumberOfPage + 1
        var tempArray = [[HMEmoticon]]()
        //遍历页数，截取相应数据
        for i in 0..<pageCount {
            //开始截取的索引
            let loc = i * NumberOfPage
            
            //截取的长度
            var len = NumberOfPage
            
            //如果数组越界，就截取剩余的个数
            if loc + len > emoticonArray.count {
                len = emoticonArray.count - loc
            }
            
            let subArray = (emoticonArray as NSArray).subarray(with: NSMakeRange(loc, len)) as! [HMEmoticon]
            tempArray.append(subArray)
        }
        
        return tempArray
    }
    
    //把被点击的表情模型保存到最近表情数组中
    func saveRecentEmoticon(emoticon:HMEmoticon) {
        //添加表情模型之前判断最近表情数组中是否存在相同的表情，如果存在就删除表情
        for (i,etn) in recentEmoticonArray.enumerated() {
            if emoticon.type == "0" {
                //代表是图片，判断最近表情数组中是否存在相同的表情描述
                if etn.chs == emoticon.chs {
                    //代表存在，删除这个表情
                    recentEmoticonArray.remove(at: i)
                    break
                }
                
            } else {
                //代表emoji，判断是否存在相同的code
                if etn.code == emoticon.code {
                    recentEmoticonArray.remove(at: i)
                    break
                }
            }
        }
        //点击表情添加到最近表情数组中的第一个元素
        recentEmoticonArray.insert(emoticon, at: 0)
        //如果超过20个表情，删除最近表情数组中的最后一个元素
        while recentEmoticonArray.count > 20 {
            recentEmoticonArray.removeLast()
        }
        //更新最近表情数组数据
        allEmoticonsArray[0][0] = recentEmoticonArray
        //把最近表情进行归档
        
        NSKeyedArchiver.archiveRootObject(recentEmoticonArray, toFile: RecentDataPath)
    }
    
    //获取沙盒路径最近表情数据
    func loadRecentEmoticonArray() -> [HMEmoticon]? {
        return NSKeyedUnarchiver.unarchiveObject(withFile: RecentDataPath) as! [HMEmoticon]?
    }
    
    //根据表情描述查找默认表情数组和浪小花表情数组里面的元素
    func selectedEmoticon(chs:String) -> HMEmoticon? {
        //在默认表情数组中查找
        for emoticon in defaultEmoticonArray {
            if emoticon.chs == chs {
                return emoticon
            }
        }
        
        //在浪小花表情数组中查找
        for emoticon in lxhEmoticonArray {
            if emoticon.chs == chs {
                return emoticon
            }
        }
        
        return nil
    }
}
